﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Hosting;
using Quartz.NET.Web.Utility;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Net;
using System.Text;

namespace Quartz.NET.Web.Controllers
{
    public class DutyController : Controller
    {
        private IHttpContextAccessor httpContextAccessor;
        private const int FEIQ_PORT = 2425;

        private readonly Encoding _gbkEncoder = Encoding.GetEncoding(936);

        private List<string> _members = new List<string> { "张三", "李四", "王五", "赵六", "小七" };

        private int _currentIndex;

        private readonly IHostEnvironment _env;

        private string IndexFile = "duty_index.txt";

        private string WeekFile = "week_index.txt";

        private string NameFile = "names.txt";

        private string ResultFile = "duty_names.txt";

        public DutyController(IHostEnvironment env, IHttpContextAccessor accessor)
        {
            _env = env;
            httpContextAccessor = accessor;
            IndexFile = Path.Combine(_env.ContentRootPath, "duty_index.txt");
            WeekFile = Path.Combine(_env.ContentRootPath, "week_index.txt");
            NameFile = Path.Combine(_env.ContentRootPath, "names.txt");
            ResultFile = Path.Combine(_env.ContentRootPath, "duty_names.txt");
        }

        [AllowAnonymous]
        [HttpPost]
        [HttpGet]
        public IActionResult Index(string ipAddress)
        {
            //IL_0035: Unknown result type (might be due to invalid IL or missing references)
            //IL_003a: Unknown result type (might be due to invalid IL or missing references)
            string text = "";
            try
            {
                List<string> list = ReadNamesFromFile();
                int current = ReadCurrentIndex();
                UpdateIndex(current, list.Count);
                Console.WriteLine("先更新");
                int num = ReadCurrentIndex();
                ValueTuple<string, string> currentDuty = GetCurrentDuty(list, num);
                string item = currentDuty.Item1;
                string item2 = currentDuty.Item2;
                UpdateIndex(num, list.Count);
                text = item + item2;
                SendMessage(ipAddress, "本周值日人员：！" + text);
            }
            catch (Exception ex)
            {
                Console.WriteLine("错误: " + ex.Message);
            }

            return Json(new
            {
                status = true,
                msg = text
            });
        }

        [AllowAnonymous]
        [HttpPost]
        [HttpGet]
        public IActionResult SeedTips(string ipAddress, string tips)
        {
            string text = "";
            try
            {
                SendMessage(ipAddress, "消息提醒：！" + tips);
            }
            catch (Exception ex)
            {
                Console.WriteLine("错误: " + ex.Message);
            }

            return Json(new
            {
                status = true,
                msg = tips
            });
        }

        public void SendMessage(string targetIP, string message)
        {
            try
            {
                string text = $"1.0:{DateTime.Now:HHmmss}:值日通知:PCNAME:32:";
                byte[] bytes = _gbkEncoder.GetBytes(text + message);
                using UdpClient udpClient = new UdpClient();
                udpClient.EnableBroadcast = true;
                IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse(targetIP), 2425);
                udpClient.Send(bytes, bytes.Length, endPoint);
            }
            catch (Exception ex)
            {
                Console.WriteLine("发送失败: " + ex.Message);
            }
        }

        private List<string> ReadNamesFromFile()
        {
            if (!FileHelper.Exists(NameFile))
            {
                throw new FileNotFoundException("名单文件不存在");
            }

            List<string> list = Enumerable.ToList(Enumerable.Where(FileHelper.ReadAllLines(NameFile), (string n) => !string.IsNullOrWhiteSpace(n)));
            if (list.Count < 2)
            {
                throw new ArgumentException("至少需要两个名字");
            }

            return list;
        }

        private int ReadCurrentIndex()
        {
            if (!FileHelper.Exists(IndexFile))
            {
                return 0;
            }

            return int.Parse(FileHelper.ReadFile(IndexFile));
        }

        private ValueTuple<string, string> GetCurrentDuty(List<string> names, int index)
        {
            //IL_0022: Unknown result type (might be due to invalid IL or missing references)
            int index2 = index % names.Count;
            int index3 = (index + 1) % names.Count;
            return new ValueTuple<string, string>(names[index2], names[index3]);
        }

        private void UpdateIndex(int current, int total)
        {
            int num = (current + 2) % total;
            if (GetWeek())
            {
                FileHelper.WriteAllText(IndexFile, num.ToString());
            }
            else
            {
                FileHelper.WriteAllText(IndexFile, current.ToString());
            }
        }

        private bool GetWeek()
        {
            int num = ((!FileHelper.Exists(WeekFile)) ? 1 : int.Parse(FileHelper.ReadFile(WeekFile)));
            DateTime today = DateTime.Today;
            int iso8601WeekOfYear = GetIso8601WeekOfYear(today);
            Console.WriteLine($"当前日期 {today:yyyy-MM-dd} 属于本年第 {iso8601WeekOfYear} 周");
            if (num != iso8601WeekOfYear)
            {
                FileHelper.WriteAllText(WeekFile, iso8601WeekOfYear.ToString());
                return true;
            }

            return false;
        }

        public static int GetIso8601WeekOfYear(DateTime date)
        {
            int num = (int)date.DayOfWeek;
            if (num == 0)
            {
                num = 7;
            }

            return CultureInfo.InvariantCulture.Calendar.GetWeekOfYear(date.AddDays(4 - num), (CalendarWeekRule)2, DayOfWeek.Monday);
        }

        [AllowAnonymous]
        [HttpPost]
        [HttpGet]
        public IActionResult ResNames()
        {
            List<string> list = ReadNamesFromFile();
            return Ok(list);
        }

        [AllowAnonymous]
        [HttpPost]
        [HttpGet]
        public IActionResult ResultNames()
        {
            if (!FileHelper.Exists(ResultFile))
            {
                throw new FileNotFoundException("名单文件不存在");
            }

            List<string> list = Enumerable.ToList(Enumerable.Where(FileHelper.ReadAllLines(ResultFile), (string n) => !string.IsNullOrWhiteSpace(n)));
            return Ok(list);
        }

        [AllowAnonymous]
        [HttpPost]
        public IActionResult SaveData([FromBody] NamesData list)
        {
            try
            {
                string[] names = list.Names;
                StringBuilder stringBuilder = new StringBuilder();
                string[] array = names;
                foreach (string value in array)
                {
                    stringBuilder.AppendLine(value);
                }

                FileHelper.WriteFile(_env.ContentRootPath, "names.txt", stringBuilder.ToString());
                return Ok(new
                {
                    success = true,
                    data = list
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine("保存名单数据失败: " + ex.Message);
                return (IActionResult)(object)((ControllerBase)this).StatusCode(500, (object)new
                {
                    success = false,
                    error = "保存名单数据时发生错误",
                    message = ex.Message
                });
            }
        }
        public IActionResult Index()
        {
            return View();
        }
    }
    public class NamesData
    {
        public string[] Names { get; set; }
    }
}
